package com.jianjun.project.monitor.online;

import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.ehcache.UtilCache;
import com.jianjun.common.constant.CacheConstants;
import com.jianjun.common.constant.HttpStatus;
import com.jianjun.common.util.UtilJackson;
import com.jianjun.framework.security.LoginUser;
import com.jianjun.framework.web.domain.AjaxResult;
import com.jianjun.framework.web.interceptor.DataScope;
import com.jianjun.framework.web.page.TableDataInfo;
import com.jianjun.project.common.domain.SysUserOnline;
import com.jianjun.project.system.user.SysUserOnlineService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * 在线用户监控
 *
 * @author source
 */
@Path(value = "/monitor/online")
public class SysUserOnlineController extends Controller {
    @Inject
    SysUserOnlineService userOnlineService;

    @DataScope(permission = "monitor:online:list")
    public void list() {
        String ipaddr = getPara("ipaddr");
        String userName = getPara("userName");
        Collection<String> keys = UtilCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        List<SysUserOnline> userOnlineList = new ArrayList<>();
        for (String key : keys) {
            LoginUser user = JsonKit.parse(UtilJackson.removeExp(UtilCache.get(key)), LoginUser.class);
            if (StrUtil.isNotEmpty(ipaddr) && StrUtil.isNotEmpty(userName)) {
                userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
            } else if (StrUtil.isNotEmpty(ipaddr)) {
                userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
            } else if (StrUtil.isNotEmpty(userName) && Objects.nonNull(user.getUser())) {
                userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
            } else {
                userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
            }
        }
        userOnlineList.removeAll(Collections.singleton(null));
        userOnlineList.sort(Comparator.comparing(SysUserOnline::getLoginTime));

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(userOnlineList);
        rspData.setTotal(userOnlineList.size());
        renderJson(rspData);
    }

    /**
     * 强退用户
     */

    @DataScope(permission = "monitor:online:forceLogout")
    public void index() {
        String tokenId = getPara();
        UtilCache.del(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
        renderJson(AjaxResult.success());
    }
}
